var app=getApp();
var ux = require('../../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {  
    nowtime: null,
    isShow: true,
    merchant: null,
    next: true,
    list: [],
    page: 0,
    size: 10,
    winheight: 0,
    winwidth: 0,
    actiona: "/api/balance/productlist.do",
    blist:[],
    tab:0,
    city: '',
    province: '',
    sums:0,
    lista:[],  
    chong:[],
    zeng:[],
    ids:[],
    agentType:1,
    action:"/api/balance/yuEOrderT.do",
    chongUrl: "/api/memberShop/chongGoodsLists.do",
	submit:"{{submit}}"
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.tab)
    this.setData({
      tab:parseInt(options.tab),
      nowtime: new Date().getTime(),
      merchant: wx.getStorageSync("banrdId")
    })
    var self = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth;
        self.setData({
          winheight: clientHeight,
          winwidth: clientWidth
        });
      }
    });
    this.setData({
      city: options.city,
      province: options.province,
      banrdId: wx.getStorageSync("banrdId")
    })
    var self=this;
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    var params = { city: this.data.city, province:this.data.province, merchant: self.data.banrdId};
    ux.request(self.data.chongUrl, params, function (data) {
      wx.hideLoading();
      var datas = data.data.list;
      for (var i = 0; i < datas.length; i++) {
        datas[i].thisCount=0;
        datas[i].thisZeng=0;
      }
        self.setData({
          blist:datas,
          lista: datas
        });
        wx.hideLoading()
      }, true)
  },
  jianCount:function(event){
    var dataset = event.currentTarget.dataset;
    var index = dataset.index;
    var lists = this.data.lista;

    if (lists[index].thisCount==0){
        return false;
     }else{
      var thisCount = lists[index].thisCount-1;
      var thisZeng = parseInt(thisCount / lists[index].howMuch) * lists[index].howMany
      lists[index].thisCount = thisCount;
      lists[index].thisZeng = thisZeng;
      this.setData({
        lista: lists
      })
      this.jisuan();
     }
  },
  jiaCount: function (event) {
    var dataset = event.currentTarget.dataset;
    var index=dataset.index;
    var lists = this.data.lista;

    var thisCount = lists[index].thisCount + 1;
    var thisZeng = parseInt(thisCount / lists[index].howMuch) * lists[index].howMany
    lists[index].thisCount=thisCount;
    lists[index].thisZeng=thisZeng;
    this.setData({
      lista: lists
    })
    this.jisuan();
  },
  jisuan:function(){
    var datas = this.data.lista;
    var chong=this.data.chong;
    var zeng=this.data.zeng;
    var ids=this.data.ids;
      chong="";
      zeng="";
      ids="";
    var sums=0;
    var yItems=[];
    for (var i = 0; i < datas.length; i++) {
      if (datas[i].thisCount>0){
        var item={};
        item.goods = datas[i].id;
        item.price = datas[i].price;
        item.chong = datas[i].thisCount;
        item.zeng = datas[i].thisZeng > 0 ? datas[i].thisZeng:0;
        item.name = datas[i].name;
        item.unit = datas[i].unit$;
        yItems.push(item);
        sums = ux.acAdd(sums, ux.acMul(datas[i].thisCount, datas[i].price));
      }

    }
    this.setData({
      jsons:yItems,
      sums: sums
    })
  },
  getData:function(id){
    var self=this;
    var parmas={goodsId:id};
    ux.request(this.data.chongUrl, parmas, function (protocol) {
      console.log(JSON.stringify(protocol.data));
      self.setData({
        agentType: protocol.dataagentType,
        goods:protocol.data.goods
      })
    }, true);
  },
  toShopDetail:function(event){
    var dataset = event.currentTarget.dataset;
      var shopid=dataset.shopid;
    var price = dataset.price;
      console.log("当前商品编号"+shopid)
      wx.navigateTo({
        url: '/pages/member/tab1/shop/detail?prices=' + price +'&id='+shopid,
      })
  },
  onForm:function(event){
	if(this.data.submit){
		  var $this = this;
		  var dataset = event.currentTarget.dataset;
		  ux.request(this.data.submit,detail.value,function(protocol){
				if(protocol.success){
					if(dataset.url){
						wx.redirectTo(dataset.url);
					}
				}
		  },true);
	 }
  },
  
  onTap:function(event){
	  var dataset = event.currentTarget.dataset;
	  var data = this.data;
	  if(dataset.key && dataset.val){
		  data[dataset.key] = dataset.val;
	  }
	  this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.isShow) {
      this.setData({
        isShow: false,
        next: true,
        list: [],
        page: 0,
        size: 10,
      })
      this.getList();   
    } 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      isShow: true
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
  toPay:function(){
    if (this.data.jsons.length==0){
      this.toast("请选择商品数量");
      return false;
    }
    wx.showLoading({
      mask: true,
      title: '处理中....'
    })
    var self = this;
    var parmas = { merchant:this.data.banrdId, sums: this.data.sums, jsons:this.data.jsons};
    console.log('sums:' + this.data.sums + 'idsw: ' + this.data.ids + 'chongw:' + this.data.chong +'zengw:'+ this.data.zeng);
    ux.request(this.data.action, parmas, function (data) {
      if (data.data.type==1){
        var order = data.data;
        wx.requestPayment({
          timeStamp: order.timeStamp,
          nonceStr: order.nonceStr,
          package: order.package,
          signType: 'MD5',
          paySign: order.paySign,
          success: function (res) {
            wx.hideLoading();
            self.toast("支付成功");
            self.setData({
              isShow:true,
              lista: self.data.blist,
              tab: 0,
              city: '',
              province: '',
              sums: 0,
              chong: [],
              zeng: [],
              ids: [],
            });
            self.onShow();
          },
          fail: function (res) {
            //console.log(JSON.stringify(res) + "为什么失败");
            wx.hideLoading();
            self.toast("支付失败");
            self.setData({
              isShow: true,
              lista: self.data.blist,
              tab: 0,
              city: '',
              province: '',
              sums: 0,
              chong: [],
              zeng: [],
              ids: [],
            });
            self.onShow();
            // var pages = getCurrentPages();
            // var currPage = pages[pages.length - 1]; //当前页面
            // var prevPage = pages[pages.length - 2]; //上一个页面
            // wx.navigateBack({
            //   delta: 1
            // })
          }
        })
      }else{
        wx.hideLoading()
        self.toast("支付失败");
      }
    }, true);
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  tojiangli:function(){
    wx.navigateTo({
      url: '/pages/protocol/fxPolicy',
    })
  },
  toqb:function(){
    wx.navigateTo({
      url: '/pages/member/tab3/wallet/ypWallet',
    })
  },
  toOne: function () {
    this.setData({
      tab: 0
    })
  },
  toTow: function () {
    this.setData({
      tab: 1
    })
  }
  ,
  
  getList: function () {
    var self = this;
    if (self.data.next == false) {
      wx.showToast({
        title: '没有更多了',
        icon: 'loading',
        duration: 1500
      });
      return;
    }
    wx.showLoading({
      mask: true,
      title: '加载中....'
    })
    var params = { banrdId: self.data.merchant, pageNo: parseInt(self.data.page), pageSize: self.data.size };
    ux.request(self.data.actiona, params, function (data) {
      var datas = data.data.list;
      console.log(JSON.stringify(datas))
      if (data.data.pageInfo.next == true) {
        self.setData({
          next: true
        });
      } else {
        self.setData({
          next: false
        });
      }
      if (self.data.page == 0) {
        self.setData({
          list: datas
        });
      } else {
        self.setData({
          list: self.data.list.concat(datas)
        });
      }
      var pages = self.data.page + 1;
      self.setData({
        page: pages
      });
      setTimeout(function () {
        wx.hideLoading()
      }, 500)
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getList();

  },
  toBack: function () {
    wx.navigateBack({
      delta: 1
    })
  }
})
